#include <math.h>

#include "user.h"

#include "user_doe.h"



double sign(double b);

double PK1(double u,double r1);

double PK2(double u,double v);

static double h,w,k,wl;

static double foc,Cos,angle;

static double R2,R1,D;



double letp(double u, double v) {

if(((u*u+v*v)>=R1*R1)&&((u*u+v*v)<R2*R2)){

  return (PK2(-v,u)-D/6*v)*k/foc;

 };

if((u*u+v*v)<R1*R1) return (PK1(v,R1))/foc*k;



//return letp(-0.015,(R2-.015));

return -1000000.;

}



double letp1(double u,double v) {

return letp(Cos*u,v);

}

void letterp()   {

   char *InputValues[6];

   char *Title={" Focusator at Letter P"};

   char *ParNames[]={"Hight              :",

		     "Width              :",

		     "Wavelength         :",

		     "Discretization Step:",

		     "Angle              :",

		     "Focal Distance     :",

		     "Focal Vertical Size:"};



   char *Default[]={

		    "    12.8          ",

		    "    12.8          ",

		    "    1.06          ",

		    "     .1           ",

		    "    0             ",

		    "    500           ",

		    "    2.0            "

		   };



   if(!sedit(25,5,7,ParNames,InputValues,Default,Title))  return ;



   // read input data

   double s;

   double a,b;

   sscanf(InputValues[0],"%lf \0",&h);

   sscanf(InputValues[1],"%lf \0",&w);

   sscanf(InputValues[2],"%lf \0",&wl);

   sscanf(InputValues[3],"%lf \0",&s);

   sscanf(InputValues[4],"%lf \0",&angle);

   Cos=cos(angle*M_PI/180);

   sscanf(InputValues[5],"%lf \0",&a);

   sscanf(InputValues[6],"%lf \0",&b);

   foc=a;

   D=b;

   R2=h/2;

   R1=R2*sqrt(3/(M_PI+3));

   k=2*M_PI/(wl*0.001);

   // max&min values of phase in this mask

   double max=letp(0.,R1-.015);

   double min=letp(-0.015,R2-.015);

   NonSymmetricDOE(Phase, max, min, letp1);

   UndoMenu(2) ;   //  delete 3 last level submenu on the screen

   // control the DOE sizes and output they to InfoWindow

   // if sizes wrong (very big) - return

   if(MessageSize(w/Cos, h, s)) return;

   // Output information to InfoWindow

   MessageName("Focus-or at Letter P");  // write title

   MessageParam(1,"Focusator at Letter P");

   MessageParam(2,"Hight  %f",h);

   MessageParam(3,"Width  %f",w);

   MessageParam(4,"Step   %f",s);

   MessageParam(5,"Angle   %f",angle);

   MessageParam(6,"Foc  = %f",a);

   MessageParam(7,"High = %f",b);

   MessageOut();                  // output all string to InfoWindow

   return;

}

/*double sign(double b)

{ if(b>0)return  1.;

  if(b<0)return -1.;

  return 0.;

};*/

double PK2(double u,double v)

{

  double C2=D/3;

  return sign(v)*C2*sqrt(u*u+v*v);

};



double PK1(double u,double r1)

{ double C=D/M_PI/r1/r1;

  return C*(r1*r1*(u*asin(u/r1)+sqrt(r1*r1-u*u)+r1*M_PI_2)-

	    pow((r1*r1-u*u),3/2)/3);

}

